package br.com.foxline.atlasmobile;

import java.io.ByteArrayOutputStream;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.Toast;
import br.com.foxline.atlasmobile.adapter.ImageAdapter;
import br.com.foxline.atlasmobile.dao.AnnexDao;
import br.com.foxline.atlasmobile.dao.ImovelDao;
import br.com.foxline.atlasmobile.entities.Annex;
import br.com.foxline.atlasmobile.entities.Imovel;
import br.com.foxline.atlasmobile.handler.CaptureActivity;

public class GalleryIssues extends Activity {

	private ImovelDao imovelDao;
	private static String IMOVEL = "getimovel";
	private ImageAdapter imageAdapter;
	private Imovel imovel;
	private String description = "";
	private Annex annex;
	private AnnexDao annexDao;
	private GridView gridView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.grid_layout);
		annexDao = new AnnexDao(getApplicationContext());
		imovelDao = new ImovelDao(getApplicationContext());
		gridView = (GridView) findViewById(R.id.grid_view);
		
		if (getIntent().getSerializableExtra(IMOVEL) != null) {
			imovel = (Imovel) getIntent().getSerializableExtra(IMOVEL);
		} else {
			imovel = new Imovel();
		}
		
		
		imageAdapter = new ImageAdapter(this, imovel);
		gridView.setAdapter(imageAdapter);
		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {

				Intent i = new Intent(getApplicationContext(),
						FullImageActivity.class);
				i.putExtra("id", position);
				i.putExtra("enviado", imovel.getEnviado());
//				i.putExtra("image", imageAdapter.getImage(position));
				i.setData(imageAdapter.mThumbUri[position]);
				startActivity(i);
			}
		});
		
		
		getActionBar().setTitle("Galeria de Imagens");
		

	}
	
	@Override
	protected void onPause() {
		super.onPause();
		try {
			finalize();
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
	
	private void removerImage() {
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_gallery, menu);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			onBackPressed();
			break;
		case R.id.image:
			Intent intent = new Intent(this, CaptureActivity.class);
			intent.putExtras(getIntent());
			startActivityForResult(intent, 100);
			break;
		case R.id.remove_image:
			removerImage();
			break;
		}
		return true;
	}



	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			dialogDescription();

			annex = (Annex) data.getSerializableExtra("annex");
			TelephonyManager tManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
			annex.setUUID(tManager.getDeviceId());
			imageAdapter.reloadResponse();
			
			annex.setImovel(imovel);
		//		if (annex.getId() == null) {
					saveResponse(annex);
				//}
				
			imageAdapter.notifyDataSetChanged();
		}
	}

	public void saveResponse(final Annex annex) {

		final ProgressDialog dialog = ProgressDialog.show(this, "",
				"Carregando...", true);
		new Thread(new Runnable() {
			@Override
			public void run() {
				annex.setContent(encodeImg(annex.getUri()));
				dialog.dismiss();
			}
		}).start();

		annexDao.create(annex);
		
	}

	private String encodeImg(String str) {
		Uri uri = Uri.parse(str);
		Bitmap decodeSampledBitmapFromResource = Util
				.decodeSampledBitmapFromResource(uri, 500, 500);

		ByteArrayOutputStream bytes = new ByteArrayOutputStream();
		decodeSampledBitmapFromResource.compress(Bitmap.CompressFormat.JPEG,
				100, bytes);
		byte[] b = bytes.toByteArray();

		return android.util.Base64.encodeToString(b,
				android.util.Base64.DEFAULT);

	}

	public void dialogDescription() {
		AlertDialog.Builder editalert = new AlertDialog.Builder(this);

		editalert.setTitle("Descrição da Imagem");
		editalert.setMessage("");

		final EditText input = new EditText(this);
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.FILL_PARENT);
		input.setLayoutParams(lp);
		editalert.setView(input);

		editalert.setPositiveButton("Confirmar",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int whichButton) {
						description = input.getText().toString();

						annex.setDescription(description);
						annexDao.update(annex);
						System.err.println(annex.getDescription());
						imageAdapter.reloadResponse();
						imageAdapter.notifyDataSetChanged();

					}
				});

		editalert.show();

	}

}